<template>
  <div class="user-manage-container">
    <a-card title="用户管理" :bordered="false" class="user-card">
      <!-- 搜索表单区域 -->
      <div class="search-form">
        <a-form
          layout="inline"
          :model="formState"
          @finish="handleFinish"
        >
          <a-form-item label="用户名">
            <a-input v-model:value="formState.userName" placeholder="请输入用户名">
              <template #prefix>
                <UserOutlined style="color: rgba(0, 0, 0, 0.25)" />
              </template>
            </a-input>
          </a-form-item>

          <a-form-item label="账号">
            <a-input v-model:value="formState.userAccount" placeholder="请输入账号">
              <template #prefix>
                <LockOutlined style="color: rgba(0, 0, 0, 0.25)" />
              </template>
            </a-input>
          </a-form-item>

          <a-form-item>
            <a-button type="primary" html-type="submit">
              查询
            </a-button>
            <a-button style="margin-left: 10px" @click="handleReset">
              重置
            </a-button>
          </a-form-item>
        </a-form>
      </div>

      <!-- 用户表格 -->
      <a-table
        :columns="columns"
        :data-source="dataList"
        :pagination="pagination"
        :loading="loading"
        @change="doTableChange"
        class="user-table"
      >
        <template #headerCell="{ column }">
          <template v-if="column.key === 'userName'">
            <UserOutlined /> {{ column.title }}
          </template>
          <template v-else-if="column.key === 'userAvatar'">
            <PictureOutlined /> {{ column.title }}
          </template>
          <template v-else-if="column.key === 'userAccount'">
            <IdcardOutlined /> {{ column.title }}
          </template>
          <template v-else-if="column.key === 'gender'">
            <UserOutlined /> {{ column.title }}
          </template>
          <template v-else-if="column.key === 'phone'">
            <PhoneOutlined /> {{ column.title }}
          </template>
          <template v-else-if="column.key === 'email'">
            <MailOutlined /> {{ column.title }}
          </template>
          <template v-else-if="column.key === 'userStatus'">
            <SafetyCertificateOutlined /> {{ column.title }}
          </template>
          <template v-else-if="column.key === 'userRole'">
            <TeamOutlined /> {{ column.title }}
          </template>
          <template v-else-if="column.key === 'createTime'">
            <CalendarOutlined /> {{ column.title }}
          </template>
          <template v-else-if="column.key === 'action'">
            <SettingOutlined /> {{ column.title }}
          </template>
        </template>

        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'userName'">
            <span class="user-name">
              {{ record.userName }}
            </span>
          </template>

          <template v-else-if="column.key === 'userAvatar'">
            <div class="avatar-container">
              <img
                class="user-avatar"
                :src="record.userAvatar || defaultAvatar"
                :alt="record.userName"
                @error="handleImageError"
              >
            </div>
          </template>

          <template v-else-if="column.key === 'createTime'">
            {{ formatDate(record.createTime) }}
          </template>

          <template v-else-if="column.key === 'userRole'">
            <a-tag v-if="record.userRole === 'admin'" color="green">管理员</a-tag>
            <a-tag v-else-if="record.userRole === 'user'" color="blue">普通用户</a-tag>
            <a-tag v-else color="default">未知</a-tag>
          </template>

          <template v-else-if="column.key === 'gender'">
            <a-tag v-if="record.gender === 1" color="blue">男</a-tag>
            <a-tag v-else-if="record.gender === 0" color="pink">女</a-tag>
            <span v-else>-</span>
          </template>

          <template v-else-if="column.key === 'userStatus'">
            <a-tag v-if="record.userStatus === 0" color="green">正常</a-tag>
            <a-tag v-else-if="record.userStatus === 1" color="red">禁用</a-tag>
            <a-tag v-else color="orange">未知</a-tag>
          </template>

          <template v-else-if="column.key === 'action'">
            <div class="action-buttons">
              <a-button type="link" size="small" @click="handleEditUser(record)">
                编辑
              </a-button>
              <a-divider type="vertical" />
              <a-button type="link" size="small" danger @click="handleDeleteUser(record)">
                删除
              </a-button>
            </div>
          </template>
        </template>
      </a-table>
    </a-card>
  </div>
</template>
<script lang="ts" setup>
import {
  UserOutlined,
  PictureOutlined,
  IdcardOutlined,
  PhoneOutlined,
  MailOutlined,
  SafetyCertificateOutlined,
  TeamOutlined,
  CalendarOutlined,
  SettingOutlined,
  LockOutlined
} from '@ant-design/icons-vue';
import { listUsingPost } from '@/api/yonghujiekou.ts'
import { computed, onMounted, reactive, ref, type UnwrapRef } from 'vue'
import { message, Modal, type TableProps } from 'ant-design-vue'
import defaultAvatar from '@/assets/avater.png'
import type { FormInstance } from 'ant-design-vue';
import PageRequestDto = API.PageRequestDto

// 表单相关
interface FormState {
  userAccount: string;
  userName: string;
}
const formState: UnwrapRef<FormState> = reactive({
  userAccount: '',
  userName: '',
});

const handleFinish = () =>{
  //重置页码
  seachParams.current = 1;
  // 将表单搜索值同步到搜索参数中
  seachParams.userName = formState.userName;
  seachParams.userAccount = formState.userAccount;
  getUserList()
};

// 重置表单
const handleReset = () => {
  formState.userName = '';
  formState.userAccount = '';
  // 重置搜索参数并重新加载数据
  seachParams.userName = '';
  seachParams.userAccount = '';
  seachParams.current = 1;
  getUserList();
};

// 编辑用户函数
const handleEditUser = (record: any) => {
  console.log('编辑用户:', record);
  // 这里可以打开编辑模态框或跳转到编辑页面
  message.info(`编辑用户: ${record.userName}`);
};

// 删除用户函数
const handleDeleteUser = (record: any) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除用户 "${record.userName}" 吗？此操作不可恢复。`,
    okText: '确认',
    cancelText: '取消',
    onOk: async () => {
      try {
        // 这里应该调用删除用户的API
        // await deleteUser(record.id);
        message.success('删除成功');
        // 重新加载用户列表
        getUserList();
      } catch (error) {
        message.error('删除失败: ' + error.message);
      }
    }
  });
};

const columns = [
  {
    title: '用户名',
    dataIndex: 'userName',
    key: 'userName',
  },
  {
    title: '头像',
    dataIndex: 'userAvatar',
    key: 'userAvatar',
    width: 80,
  },
  {
    title: '账号',
    dataIndex: 'userAccount',
    key: 'userAccount',
  },
  {
    title: '性别',
    dataIndex: 'gender',
    key: 'gender',
    width: 80,
  },
  {
    title: '电话',
    dataIndex: 'phone',
    key: 'phone',
  },
  {
    title: '邮箱',
    dataIndex: 'email',
    key: 'email',
  },
  {
    title: '状态',
    key: 'userStatus',
    dataIndex: 'userStatus',
    width: 100,
  },
  {
    title: '角色',
    key: 'userRole',
    dataIndex: 'userRole',
    width: 100,
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    width: 120,
  },
  {
    title: '操作',
    key: 'action',
    width: 150,
  },
];

// 用户列表
const dataList = ref<PageRequestDto[]>([]);
const total = ref(0);
const loading = ref(false);

// 搜索条件
const seachParams = reactive<API.PageRequestDto>({
  current: 1,
  pageSize: 10
})

// 获取用户列表
const getUserList = async () => {
  loading.value = true;
  try {
    const res = await listUsingPost({
      ...seachParams
    })
    if (res.data?.data) {
      dataList.value = res.data.data.records ?? [];
      total.value = res.data.data.total ?? 0;
    } else {
      message.error('获取用户列表失败');
    }
  } catch (error) {
    message.error('获取用户列表失败: ' + error.message);
  } finally {
    loading.value = false;
  }
}

const pagination = computed(() => ({
  current: seachParams.current ?? 1,
  pageSize: seachParams.pageSize ?? 10,
  total: total.value,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total) => `共 ${total} 条数据`,
  pageSizeOptions: ['10', '20', '50', '100'],
}));

// 时间格式化
const formatDate = (dateString: string) => {
  if (!dateString) return '-';
  const date = new Date(dateString);
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  });
};

// 处理图片加载错误
const handleImageError = (e: Event) => {
  const target = e.target as HTMLImageElement;
  target.src = defaultAvatar;
};

// 页面加载时获取用户列表
onMounted(() => {
  getUserList();
})

// 表格变化
const doTableChange: TableProps['onChange'] = (pagination) => {
  seachParams.current = pagination.current;
  seachParams.pageSize = pagination.pageSize;
  getUserList();
};
</script>
<style scoped>
.user-manage-container {
  padding: 20px;
  background-color: #f0f2f5;
  min-height: calc(100vh - 64px);
}

.user-card {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.search-form {
  padding: 20px;
  background: #fafafa;
  border-radius: 6px;
  margin-bottom: 20px;
}

.user-table {
  margin-top: 20px;
}

.user-name {
  font-weight: 500;
  color: #1890ff;
}

.avatar-container {
  display: flex;
  justify-content: center;
  align-items: center;
}

.user-avatar {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  object-fit: cover;
  border: 1px solid #e8e8e8;
}

.action-buttons {
  display: flex;
  align-items: center;
}

.action-buttons :deep(.ant-btn-link) {
  padding: 0;
}
</style>

